<script setup lang="ts">
import { ElMessage, ElMessageBox, FormInstance, FormRules } from "element-plus";
import { nextTick, onMounted, reactive, ref } from "vue";
import { ApiClassroom } from "../../api";

const list = ref<UI.Get[]>([]);
onMounted(async () => {
  list.value = await ApiClassroom.get();
});
const show = ref<boolean>(false);
const model = reactive<API.Classroom.Update>({ clsr_id: 0, clsr_name: "" });
const formRef = ref<FormInstance | null>(null);
const emits = defineEmits<{ (name: "save", model: API.Classroom.Add): void }>();
const cancel = async () => {
  await ElMessageBox.confirm("取消数据会丢失哦？", "提示", { type: "warning" });
  show.value = false;
};
const save = async () => {
  await formRef.value?.validate();
  await ApiClassroom.update(model);
  emits("save", model);
  ElMessage.success("修改成功");
  show.value = false;
};
const roules: FormRules = {
  clsr_name: [
   
    { //@ts-ignore
      validator: (rule, value, cb) => {
        if (
          list.value.some((item: UI.Get) =>item.clsr_name === value && item.clsr_id !== model.clsr_id)) {
          cb(new Error("该教室已存在"));
        } else {
          cb();
        }
      },trigger: "blur"
    },
    { required: true, message: "请输入教室名称", trigger: "blur" },
    { min: 2, max: 10, message: "长度在2-10个字符", trigger: "blur" },
  ],
};
defineExpose({
  begin: (data: API.Classroom.Update) => {
    model.clsr_id = data.clsr_id;
    model.clsr_name = data.clsr_name;
    nextTick(() => (show.value = true));
  },
});
</script>

<template>
  <el-dialog title="新增教室" width="300px" v-model="show">
    <el-form ref="formRef" :model="model" label-width="80px" :rules="roules">
      <el-form-item label="教室名称" prop="clsr_name">
        <el-input
          v-model="model.clsr_name"
          placeholder="请输入教室名称"
        ></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </div>
  </el-dialog>
</template>

<style scoped></style>
